package com.alibaba.citrus.ots.platform.enhance.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.platform.enhance.repository.CompanyRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.model.DubboResult;
import com.alibaba.citrus.ots.platform.enhance.repository.utils.ResultUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineCreateCompanyRequest;
import com.epoch.app.bcots.model.dto.BaselineQueryCompanyByIdRequest;
import com.epoch.app.bcots.model.dto.BaselineQueryCompanyByPageRequest;
import com.epoch.app.bcots.model.dto.BaselineUpdateCompanyRequest;
import com.epoch.app.bcots.model.dto.BaselineUpdateCompanyStatusRequest;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.dto.request.QueryCompanyRequest;
import com.epoch.app.otsplatformenhance.sdo.CompanySDO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/9/3 15:01
 */
@Component
public class CompanyRepositoryImpl implements CompanyRepository {

    Log log = Log.getLogger(CompanyRepositoryImpl.class);

    @Resource
    BaseDataService baseDataService;

    @Override
    @RepositoryInvoker
    public Result<Boolean> createCompany(CompanySDO sdo) {
        BaselineCreateCompanyRequest createRequest = createRequestConverter(sdo);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineCreateCompany(createRequest));
        if(!result.getSuccess()){
            log.error("创建公司信息失败=={}，错误原因=={}",sdo.toString(),result.getMessage());
            return Result.fail("",result.getMessage());
        }
        return Result.success(result.getSuccess());
    }

    @Override
    @RepositoryInvoker
    public Result<Boolean> editCompany(CompanySDO sdo) {
        BaselineUpdateCompanyRequest updateRequest = updateRequestConverter(sdo);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineUpdateCompany(updateRequest));
        if(!result.getSuccess()){
            log.error("编辑公司信息失败=={}，错误原因=={}",sdo.toString(),result.getMessage());
            return Result.fail("",result.getMessage());
        }
        return Result.success(result.getSuccess());
    }

    @Override
    @RepositoryInvoker
    public Result<Boolean> updateCompanyStatus(CompanySDO sdo) {
        BaselineUpdateCompanyStatusRequest updateCompanyStatusRequest = updateStatusRequestConverter(sdo);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineUpdateCompanyStatus(updateCompanyStatusRequest));
        if(!result.getSuccess()){
            log.error("编辑公司信息失败=={}，错误原因=={}",sdo.toString(),result.getMessage());
            return Result.fail("",result.getMessage());
        }
        return Result.success(result.getSuccess());
    }

    @Override
    @RepositoryInvoker
    public CompanySDO getCompany(String companyId) {
        BaselineQueryCompanyByIdRequest request = BaselineQueryCompanyByIdRequest.builder()
                .id(companyId)
                .build();
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineQueryCompanyById(request));
        CompanySDO companySDO = companySDOConverter((Map) result.getResult());
        return companySDO;
    }

    @Override
    @RepositoryInvoker
    public PageResult<List<CompanySDO>> pageQueryCompanyList(QueryCompanyRequest request) {
        if(request == null){
            request = new QueryCompanyRequest();
        }
        BaselineQueryCompanyByPageRequest queryRequest = loadListRequestConverter(request);
        DubboResult result = ResultUtils.getDubboPageResult((Map)baseDataService.baselineQueryCompanyByPage(queryRequest));
        List<Map<String,Object>> list = (List<Map<String, Object>>) result.getResult();
        List<CompanySDO> data = list.stream().map( bean -> {
            return companySDOConverter(bean);
        }).collect(Collectors.toList());
        return PageResult.of(data,result.getTotal());
    }

    private BaselineCreateCompanyRequest createRequestConverter(CompanySDO sdo){
        BaselineCreateCompanyRequest createRequest = new BaselineCreateCompanyRequest();
        createRequest.setName(sdo.getName());
        createRequest.setCode(sdo.getCode());
        createRequest.setOutCode(sdo.getOutCode());
        createRequest.setUnifiedSocialCreditCode(sdo.getSocialCreditCode());
        createRequest.setDesc(sdo.getDesc());
        createRequest.setOperatorId(sdo.getOperatorId());
        Map<String,Object> features = new HashMap<>();
        features.put("type",sdo.getType());
        features.put("legalPerson",sdo.getLegalPerson());
        features.put("registrationProvinceCode",sdo.getRegistrationProvinceCode());
        features.put("registrationCityCode",sdo.getRegistrationCityCode());
        features.put("registrationAreaCode",sdo.getRegistrationAreaCode());
        features.put("registrationAddress",sdo.getRegistrationAddress());
        features.put("businessPerson",sdo.getBusinessPerson());
        createRequest.setFeatures(JSON.toJSONString(features));
        return createRequest;
    }

    private BaselineUpdateCompanyRequest updateRequestConverter(CompanySDO sdo){
        BaselineUpdateCompanyRequest updateRequest = new BaselineUpdateCompanyRequest();
        updateRequest.setName(sdo.getName());
        updateRequest.setCode(sdo.getCode());
        updateRequest.setOutCode(sdo.getOutCode());
        updateRequest.setUnifiedSocialCreditCode(sdo.getSocialCreditCode());
        updateRequest.setDesc(sdo.getDesc());
        updateRequest.setOperatorId(sdo.getOperatorId());
        Map<String,Object> features = new HashMap<>();
        features.put("type",sdo.getType());
        features.put("legalPerson",sdo.getLegalPerson());
        features.put("registrationProvinceCode",sdo.getRegistrationProvinceCode());
        features.put("registrationCityCode",sdo.getRegistrationCityCode());
        features.put("registrationAreaCode",sdo.getRegistrationAreaCode());
        features.put("registrationAddress",sdo.getRegistrationAddress());
        features.put("businessPerson",sdo.getBusinessPerson());
        updateRequest.setFeatures(JSON.toJSONString(features));
        updateRequest.setVersion(sdo.getVersion());
        updateRequest.setId(sdo.getId());
        return updateRequest;
    }

    private BaselineUpdateCompanyStatusRequest updateStatusRequestConverter(CompanySDO sdo){
        BaselineUpdateCompanyStatusRequest updateCompanyStatusRequest = new BaselineUpdateCompanyStatusRequest();
        updateCompanyStatusRequest.setOperatorId(sdo.getOperatorId());
        updateCompanyStatusRequest.setStatus(sdo.getStatus());
        updateCompanyStatusRequest.setVersion(sdo.getVersion());
        updateCompanyStatusRequest.setId(sdo.getId());
        return updateCompanyStatusRequest;
    }

    private CompanySDO companySDOConverter(Map map) {
        if(StringUtil.isBlank((String)map.get("id"))){
            return null;
        }
        CompanySDO companySDO = new CompanySDO();
        companySDO.setId((String) map.get("id"));
        companySDO.setName((String) map.get("name"));
        companySDO.setCode((String) map.get("code"));
        companySDO.setOutCode((String) map.get("outCode"));
        companySDO.setDesc((String) map.get("desc"));
        companySDO.setSocialCreditCode((String) map.get("unifiedSocialCreditCode"));
        companySDO.setStatus(((Double) map.get("status")).intValue());
        companySDO.setVersion(((Double) map.get("version")).intValue());
        String features = (String) map.get("features");
        Map jsonObj = JSON.parseObject(features);
        companySDO.setType((Integer) jsonObj.get("type"));
        companySDO.setLegalPerson((String) jsonObj.get("legalPerson"));
        companySDO.setRegistrationProvinceCode((String) jsonObj.get("registrationProvinceCode"));
        companySDO.setRegistrationCityCode((String) jsonObj.get("registrationCityCode"));
        companySDO.setRegistrationAreaCode((String) jsonObj.get("registrationAreaCode"));
        companySDO.setRegistrationAddress((String) jsonObj.get("registrationAddress"));
        companySDO.setBusinessPerson((String) jsonObj.get("businessPerson"));
        return companySDO;
    }

    private BaselineQueryCompanyByPageRequest loadListRequestConverter(QueryCompanyRequest request){
        BaselineQueryCompanyByPageRequest queryCompanyByPageRequest = BaselineQueryCompanyByPageRequest.builder()
                .start(request.getStart())
                .limit(request.getLimit())
                .ids(request.getIds())
                .name(request.getName())
                .code(request.getCode())
                .outCode(request.getOutCode())
                .socialCreditCode(request.getSocialCreditCode())
                .status(request.getStatus())
                .build();
        return queryCompanyByPageRequest;
    }

}
